package io.wdb.wxapp.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.wdb.common.exception.RspCodeEnum;
import io.wdb.common.utils.R;
import io.wdb.modules.activity.wxapp.entity.HdActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdCardInitiatorEntity;
import io.wdb.modules.activity.wxapp.entity.HdUserEntity;
import io.wdb.modules.activity.wxapp.service.HdActivityService;
import io.wdb.modules.activity.wxapp.service.HdCardInitiatorService;
import io.wdb.modules.activity.wxapp.service.HdUserService;
import io.wdb.wxapp.model.HdActivityModel;
import io.wdb.wxapp.model.HdUserModel;

/**
 * @author zeteng
 */
@Controller
@RequestMapping("/")
@Api(tags="A.all Activity Info" ) 
public class HdActivityController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(HdActivityController.class);
	@Autowired
	private HdActivityService hdActivityService;
	@Autowired
	private HdCardInitiatorService hdCardInitiatorService;
	@Autowired
	private HdUserService hdUserService;
	
	@RequestMapping(value="isActivity",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="当前运营活动是否开启", notes="【type必传（1裂变活动,2阅读排行）】\t appid和openid传递后会返回当前openid用户信息和参与活动信息"
			+ ",返回activity为null则活动不存在或已终止,返回activityId在发起活动时需要,不存在hdUserId在参与活动时需要调起登录")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "type",value = "活动类型", dataType = "int", paramType = "query",required=true),
		@ApiImplicitParam(name = "userid",value = "userid", dataType = "Long", paramType = "query"),
		@ApiImplicitParam(name = "mobile",value = "mobile", dataType = "String", paramType = "query"),
		@ApiImplicitParam(name = "usertoken",value = "usertoken", dataType = "String", paramType = "query")
	})
	public R isActivity(HttpServletRequest request){
		checkIsNull(request.getParameter("type"), "type");
		Map<String, Object> params = new HashMap<>();
		params.put("type", request.getParameter("type"));
		logger.info("isActivity:{}",params);
		List<HdActivityEntity> hdActivityList = hdActivityService.queryList(params);
		Map<String, Object> result = new HashMap<>();
		result.put("activity", HdActivityModel.convert(hdActivityList));
		
		String userid = request.getParameter("userid");
		String usertoken = request.getParameter("usertoken");
		String mobile = request.getParameter("mobile");
		checkIsNull(usertoken, "usertoken");
		HdUserEntity hdUserEntity = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);
		if(isEmpty(hdUserEntity) || isEmpty(hdUserEntity.getSessionKey())) {//如果返回为空，表示usertoken过期
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		//根据userid和usertoken查询用户是否参与过当前活动
		if (hdActivityList != null && hdActivityList.size() > 0 && !isEmpty(hdUserEntity.getWxOpenid())
				&& !isEmpty(hdUserEntity.getWxAppid())) {
			Map<String, Object> initiator = new HashMap<>();
			initiator.put("activityId", hdActivityList.get(0).getId());
			initiator.put("userId", hdUserEntity.getId());
			List<HdCardInitiatorEntity> init = hdCardInitiatorService.queryList(initiator);
			result.put("userinfo", HdUserModel.convert(hdUserEntity));// 一个微信只能绑定一个手机号，可换
			result.put("cardInfo", init);// 参与活动的信息
		}
		return R.ok(result);
	}
	
	@RequestMapping(value="activityList",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="活动中心", notes="所有有效活动")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pagesize",value = "pagesize", dataType = "int", paramType = "query"),
		@ApiImplicitParam(name = "pageno",value = "pageno", dataType = "int", paramType = "query"),

	})
	public R activityList(HttpServletRequest request) {
		String pagesize = request.getParameter("pagesize");
		String pagno = request.getParameter("pageno");
		Map<String, Object> params = new HashMap<>();
		//params.put("available", 1);
		if(!ObjectUtils.isEmpty(pagesize) && !ObjectUtils.isEmpty(pagno)) {
			params.put("offset", (Integer.valueOf(pagno)-1) * Integer.valueOf(pagesize));
			params.put("limit", Integer.valueOf(pagesize));
		}
		
		params.put("sidx", "priority");
		params.put("order", "desc");


		List<HdActivityEntity> hdActivityList = hdActivityService.queryList(params);
		Map<String, Object> result = new HashMap<>();
		result.put("activity", HdActivityModel.convert(hdActivityList));
		return R.ok(result);
	}
	
	@RequestMapping(value="activityCount",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="活动数量", notes="所有有效活动")
	public R activityCount(HttpServletRequest request) {
		Map<String, Object> params = new HashMap<>();
		params.put("available", 1);
		
		List<HdActivityEntity> hdActivityList = hdActivityService.queryList(params);
		Map<String, Object> result = new HashMap<>();
		result.put("activityCount", hdActivityList.size());
		return R.ok(result);
	}
	
}
